package com.lagou.wechat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.lagou.commons.HttpClientUtil;
import com.lagou.entity.Token;
import com.lagou.entity.User;
import com.lagou.entity.UserDTO;
import com.lagou.entity.WxUser;
import com.lagou.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("user")
public class WechatLoginController {
    @Reference
    private UserService userService;

    // 是否用微信登录成功
    private UserDTO userDTO = null;

    @GetMapping("wxlogin")
    public Object wechatLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1.微信官方授权code
        String code = request.getParameter("code");
        System.out.println("【临时凭证】code = " + code);

        // 2.通过code换取access_token
        String getTokenByCodeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code=" + code +
                "&grant_type=authorization_code";
        String tokenString = HttpClientUtil.doGet(getTokenByCodeUrl);
        System.out.println("tokenString = " + tokenString);
        // 将json格式的token字符串转换成实体对象，方便存和取
        Token token = JSON.parseObject(tokenString, Token.class);

        // 3. 通过token，去微信官方获取用户的信息
        String getUserByTokenUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
                token.getAccess_token() + "&openid=" + token.getOpenid();
        String userInfoString = HttpClientUtil.doGet(getUserByTokenUrl);
        System.out.println("userInfoString = " + userInfoString);
        // 将json格式的user字符串转换成实体对象，方便存和取
        WxUser wxUser = JSON.parseObject(userInfoString, WxUser.class);
//        System.out.println("微信用户昵称 = " + wxUser.getNickname());
//        System.out.println("微信用户头像 = " + wxUser.getHeadimgurl());

        // 拉勾的业务流程! 需要 手机号(wxUser.getUnionid())和密码 (wxUser.getUnionid()),头像和昵称
//        UserDTO dto = new UserDTO();
        System.out.println("phone = " + wxUser.getUnionid());
        System.out.println("password = " + wxUser.getUnionid());
        System.out.println("nickname = " + wxUser.getNickname());
        System.out.println("portrait = " + wxUser.getHeadimgurl());

        //检测手机号是否注册
        Integer i = userService.checkPhone(wxUser.getUnionid());
        if (i == 0) {
            //注册
            userService.register(wxUser.getUnionid(), wxUser.getUnionid(), wxUser.getNickname(), wxUser.getHeadimgurl());
        }

        //登录
        User user = userService.login(wxUser.getUnionid(), wxUser.getUnionid());
        userDTO = new UserDTO();
        if (user != null) {
            userDTO.setState(200);
            userDTO.setMessage(i == 0 ? "手机号尚未注册，系统已帮您自动注册并登录，请牢记密码！" : "登录成功！");
            System.out.println(i == 0 ? "手机号尚未注册，系统已帮您自动注册并登录，请牢记密码！" : "登录成功！");
        } else {
            userDTO.setState(500);
            userDTO.setMessage("账号密码不匹配，登录失败！");
            System.out.println("账号密码不匹配，登录失败！");
        }
        userDTO.setContent(user);
        response.sendRedirect("http://localhost:8081");

        return null;
    }

    @GetMapping("checkWxStatus")
    public UserDTO checkWxStatus() {
        return userDTO;
    }

    @GetMapping("logout")
    public Object logout() {
        userDTO = null;
        return null;
    }
}
